﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZKLibrarys.zkem
{
    public class ZKConfig
    {
        #region 定义类
        /// <summary>
        /// 中控配置元素
        /// </summary>
        public sealed class ZKConfigElement : ConfigurationElement
        {
            public ZKConfigElement(string id, string name, string ip, int port, int password)
            {
                ID = id;
                Name = name;
                IP = ip;
                Port = port;
                Password = password;
            }

            public ZKConfigElement()
            {
                //默认初始化数据
                Port = 4370;
                Password = 0;
            }

            [ConfigurationProperty("id", DefaultValue = "0", IsRequired = true, IsKey = true)]
            public string ID
            {
                get { return (string)this["id"]; }
                set { this["id"] = value; }
            }
            [ConfigurationProperty("name", DefaultValue = "0")]
            public string Name
            {
                get { return (string)this["name"]; }
                set { this["name"] = value; }
            }
            [ConfigurationProperty("ip", DefaultValue = "0.0.0.0")]
            public string IP
            {
                get { return (string)this["ip"]; }
                set { this["ip"] = value; }
            }
            [ConfigurationProperty("port", DefaultValue = "4370")]
            public int Port
            {
                get { return (int)this["port"]; }
                set { this["port"] = value; }
            }
            [ConfigurationProperty("password", DefaultValue = "0")]
            public int Password
            {
                get { return (int)this["password"]; }
                set { this["password"] = value; }
            }
        }

        /// <summary>
        /// 中控配置元素集合
        /// </summary>
        public sealed class ZKConfigElementCollection : ConfigurationElementCollection
        {
            public ZKConfigElementCollection()
            {

            }

            /// <summary>
            /// 创建新的中控配置节元素
            /// </summary>
            /// <returns>ConfigurationElement</returns>
            protected override ConfigurationElement CreateNewElement()
            {
                return new ZKConfigElement();
            }

            /// <summary>
            /// 获取中控配置节元素的ID
            /// </summary>
            /// <param name="element">配置节元素</param>
            /// <returns>Object</returns>
            protected override object GetElementKey(ConfigurationElement element)
            {
                return ((ZKConfigElement)element).ID;
            }

            /// <summary>
            /// 获取指定中控配置元素
            /// </summary>
            /// <param name="index">定位索引</param>
            /// <returns></returns>
            public ZKConfigElement this[int index]
            {
                get
                {
                    return (ZKConfigElement)BaseGet(index);
                }
                set
                {
                    if (BaseGet(index) != null)
                    {
                        BaseRemoveAt(index);
                    }
                    BaseAdd(index, value);
                }
            }
            
            /// <summary>
            /// 获取指定中控配置元素
            /// </summary>
            /// <param name="ID">ID</param>
            /// <returns></returns>
            public new ZKConfigElement this[string ID]
            {
                get
                {
                    return (ZKConfigElement)BaseGet(ID);
                }
            }
            

            /// <summary>
            /// 添加中控配置元素到配置集
            /// </summary>
            /// <param name="element">中控配置元素对象</param>
            public void Add(ZKConfigElement element)
            {
                BaseAdd(element);
            }

            /// <summary>
            /// 重写BaseAdd,在添加元素时即使重复也不引发异常
            /// </summary>
            /// <param name="element">要添加的元素</param>
            protected override void BaseAdd(ConfigurationElement element)
            {
                BaseAdd(element, false);//添加重复不引发异常
            }

            /// <summary>
            /// 清除中控配置集中的所有元素
            /// </summary>
            public void Clear()
            {
                BaseClear();
            }

            /// <summary>
            /// 删除中控配置集中的指定元素
            /// </summary>
            /// <param name="ID">机器号</param>
            public void Remove(string ID)
            {
                BaseRemove(ID);
            }
        }

        /// <summary>
        /// 中控配置节
        /// </summary>
        public sealed class ZKConfigSection : ConfigurationSection
        {
            public ZKConfigSection()
            {
                Desc = "init";
            }

            /// <summary>
            /// 节备注
            /// </summary>
            [ConfigurationProperty("desc", DefaultValue = "", IsRequired = false)]
            public string Desc
            {
                get { return (string)this["desc"]; }
                set { this["desc"] = value; }
            }

            /// <summary>
            /// 自定义节所有元素
            /// </summary>
            [ConfigurationProperty("devices", IsDefaultCollection = false)]
            [ConfigurationCollection(typeof(ZKConfigElementCollection), AddItemName = "add", ClearItemsName = "clear")]
            public ZKConfigElementCollection Devices
            {
                get
                {
                    ZKConfigElementCollection customAppElementCollection = (ZKConfigElementCollection)this["devices"];
                    return customAppElementCollection;
                }
                set
                {
                    ZKConfigElementCollection customAppElementCollection = value;
                }
            }
        }
        #endregion

        #region 配置文件操作方法
        /// <summary>
        /// 初始化中控配置节
        /// 不存在节就添加
        /// 存在节就更新一下Desc文字
        /// </summary>
        public static void InitZKConfig()
        {
            string desc = "中控设备配置信息";
            ZKConfigSection section = new ZKConfigSection
            {
                Desc = desc
            };
            //section.Devices.Clear();
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                config.Sections.Add("ZKConfigSection", section);
            }
            else
            {
                ((ZKConfigSection)config.Sections["ZKConfigSection"]).Desc = desc;
                //((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices.Clear();
            }
            config.Save();
        }

        /// <summary>
        /// 添加更新设备
        /// </summary>
        /// <param name="id">机器号</param>
        /// <param name="name">名称</param>
        /// <param name="ip">IP地址</param>
        /// <param name="port">端口</param>
        /// <param name="pass">密码</param>
        public static void AddDevice(string id, string name, string ip, int port, int pass)
        {
            ZKConfigElement element = new ZKConfigElement(id, name, ip, port, pass);
            Console.WriteLine($"id{id},name{name},ip{ip}port{port}pass{pass}");
            AddDevice(element);
        }

        /// <summary>
        /// 添加更新设备
        /// </summary>
        /// <param name="element">中控配置设备元素对象</param>
        public static void AddDevice(ZKConfigElement element)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
            }
            ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices.Add(element);
            config.Save();
        }

        /// <summary>
        /// 删除设备元素
        /// </summary>
        /// <param name="ID">机器号</param>
        public static void DelDevice(string ID)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
            }
            ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices.Remove(ID);
            config.Save();
        }

        /// <summary>
        /// 删除设备元素
        /// </summary>
        /// <param name="element">中控配置设备元素对象</param>
        public static void DelDevice(ZKConfigElement element)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
            }
            ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices.Remove(element.ID);
            config.Save();
        }

        /// <summary>
        /// 获取中控设备配置
        /// </summary>
        /// <param name="ID">机器号</param>
        /// <returns>KeyValue</returns>
        public static Dictionary<string, string> GetDevice(string ID)
        {
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
                return null;
            }
            if (((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices[ID] == null)
            {
                return null;
            }
            else
            {
                ZKConfigElement element = ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices[ID];
                keyValues.Add("ID", element.ID.ToString());
                keyValues.Add("Name", element.Name);
                keyValues.Add("IP", element.IP);
                keyValues.Add("Port", element.Port.ToString());
                keyValues.Add("Password", element.Password.ToString());
                return keyValues;
            }
        }

        /// <summary>
        /// 获取所有中控设备配置
        /// </summary>
        /// <returns></returns>
        public static List<string[]> GetDevices()
        {
            List<string[]> lss = new List<string[]>();
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
                return null;
            }
            if (((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices.Count <= 0)
            {
                return lss;
            }
            else
            {
                foreach (ZKConfigElement item in ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices)
                {
                    string[] tmp = new string[5];
                    tmp[0] = item.ID.ToString();
                    tmp[1] = item.Name.ToString();
                    tmp[2] = item.IP.ToString();
                    tmp[3] = item.Port.ToString();
                    tmp[4] = item.Password.ToString();
                    lss.Add(tmp);
                }
                return lss;
            }
        }

        /// <summary>
        /// 检测是否存在指定设备配置元素
        /// </summary>
        /// <param name="ID">机器号</param>
        /// <returns></returns>
        public static bool HaveDevice(string ID)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
                return false;
            }
            ZKConfigElementCollection y = ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices;
            var z = y[ID.ToString()];
            if (((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices[ID] == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 清空所有设备配置元素
        /// </summary>
        public static void DelDevices()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections["ZKConfigSection"] == null)
            {
                InitZKConfig();
            }
            ((ZKConfigSection)config.Sections["ZKConfigSection"]).Devices.Clear();
            config.Save();
        }
        #endregion
    }
}
